<template>
  <el-container>
    <el-aside width="300px">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="工程位置" name="second">
          <span>项目</span>
          <!-- {{projectList.name}} -->
          <el-tooltip class="item" effect="dark" content="添加节点" placement="bottom">
            <i class="el-icon-circle-plus-outline treeAdd" @click="treeAdd = true"></i>
          </el-tooltip>
          <el-tree
            :data="data5"
            :props="props"
            node-key="id"           
            highlight-current
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{node, data}">
              <span size="mini" @click="() => button(data)">{{node.label}}</span>
              <span>
                <el-button type="text" size="mini" @click="() => append(data)">添加</el-button>
                <el-button type="text" size="mini" @click="() => edit(data)">编辑</el-button>
                <el-button type="text" size="mini" @click="remove(node, data)">删除</el-button>
              </span>
            </span>
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="监测项目" name="first">监测项目</el-tab-pane>
      </el-tabs>
    </el-aside>
    <el-main v-if="elmain">
      <el-col :span="24" class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <b>{{mainTable.mianBreadcrumb}}</b>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>

      <el-col :span="24">
        <el-button type="primary" class="button-add" @click="buttonAdd = true">
          <i class="el-icon-edit"></i>创建测点
        </el-button>
        <el-button type="primary" class="button-add" @click="relevance = true">关联测点</el-button>
      </el-col>

      <el-col :span="24">
        <el-table :data="tableData" stripe highlight-current-row class="table">
          <el-table-column type="index" width="60"></el-table-column>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="collectName" label="绑定设备名称"></el-table-column>
          <el-table-column prop="monitorContent.name" label="监测项"></el-table-column>
          <el-table-column prop="createTime" :formatter="dateFormat" label="创建时间" width="160"></el-table-column>
          <el-table-column prop="status" label="状态"></el-table-column>
          <el-table-column prop="operation" label="操作">
            <template slot-scope="scope">
              <el-button @click="deleteRow(scope.$index,scope.row)" type="text" size="small">移除</el-button>
              <el-button type="text" @click="handleEdit(scope.$index, scope.row)" size="small">编辑</el-button>
              <el-button type="text" @click="allocaTion(scope.$index, scope.row)" size="small">配置</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <span class="show-pager">显示总数</span>
          <el-pagination
            @current-change="handleCurrentChange"
            @pre-click="handlePreClick"
            @next-click="handleNextClick"
            :current-page.sync="currentPage"
            :page-size="10"
            layout="total, prev, pager, next"
            :total="totalRecord"
          ></el-pagination>
        </div>
      </el-col>
    </el-main>

    <el-dialog title="添加" :visible.sync="treeAdd" :modal="false">
      <el-form :model="form">
        <el-form-item :label-width="formLabelWidth" label="名称：">
          <el-input v-model="form.name" :placeholder="form.name" class="input-w-220"></el-input>
        </el-form-item>
        <el-form-item label="分组类型：" :label-width="formLabelWidth" @change="selectKey">
          <el-select v-model="form.treeType" clearable placeholder="请选择">
            <el-option v-for="item in treeType" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class>
        <el-button @click="treeAdd = false">取消</el-button>
        <el-button type="primary" @click="submitTreeAdd">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="'关联测点('+row.name+')'" :visible.sync="relevance" :modal="false">
      <el-form :model="relevan">
        <el-form-item :label-width="formLabelWidth">
          <el-transfer
            filterable
            filter-placeholder="请输入测点名称"
            v-model="yesData"
            :props="{
                        key: 'id',
                        label: 'name'
                      }"
            :titles="['未关联', '已关联']"
            @change="handleChange"
            :data="noData"
          ></el-transfer>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="添加" :visible.sync="treeNodeadd" :modal="false">
      <el-form :model="treeNodeAdddata">
        <el-form-item :label-width="formLabelWidth" label="名称：">
          <el-input v-model="treeNodeAdddata.name" placeholder="请输入名称" class="input-w-220"></el-input>
        </el-form-item>
        <el-form-item label="分组类型：" :label-width="formLabelWidth">
          <el-select
            v-model="treeNodeAdddata.treeType"
            clearable
            placeholder="请选择"
            @change="selectKey"
          >
            <el-option v-for="item in treeType" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class>
        <el-button @click="treeNodeadd = false">取消</el-button>
        <el-button type="primary" @click="submitTreeNodeAdd">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="treeNodeEdit" :modal="false">
      <el-form :model="treeNodeEditdata">
        <el-form-item :label-width="formLabelWidth" label="名称：">
          <el-input
            v-model="treeNodeEditdata.name"
            :placeholder="treeNodeEditdata.name"
            class="input-w-220"
          ></el-input>
        </el-form-item>
        <el-form-item label="分组类型：" :label-width="formLabelWidth">
          <el-select
            v-model="treeNodeEditdata.treeType"
            clearable
            :placeholder="treeType.name"
            @change="selectKey1"
          >
            <el-option v-for="item in treeType" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class>
        <el-button @click="treeNodeEdit = false">取消</el-button>
        <el-button type="primary" @click="submitTreeNodeEdit">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加测点" :visible.sync="buttonAdd" :modal="false">
      <el-form :model="devicePointsAdd">
        <el-form-item label="名称：" :label-width="formLabelWidth">
          <el-input v-model="devicePointsAdd.name" placeholder="请输入名称" class="input-w-480"></el-input>
        </el-form-item>
        <el-form-item label="监测项：" :label-width="formLabelWidth">
          <el-select
            v-model="devicePointsAddmonitorContent"
            placeholder="请选择"
            class="input-w-480"
            @change="monitorContentSelectKey"
          >
            <el-option
              v-for="item in monitorContent"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="传感器：" :label-width="formLabelWidth">
          <el-select
            v-model="devicePointsAddsensor"
            placeholder="请选择"
            class="input-w-480"
            @change="sensorSelectKey"
          >
            <el-option v-for="item in sensor" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="buttonAdd = false">取消</el-button>
        <el-button type="primary" @click="submitButtonAdd">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑测点" :visible.sync="buttonEdit" :modal="false">
      <el-form :model="devicePointsEdit">
        <el-form-item label="名称：" :label-width="formLabelWidth">
          <el-input v-model="devicePointsEdit.name" placeholder="请输入名称" class="input-w-480"></el-input>
        </el-form-item>
        <el-form-item label="传感器：" :label-width="formLabelWidth">
          <el-select
            v-model="devicePointsEditsensor"
            :placeholder="sensorName"
            class="input-w-480"
            @change="sensorSelectKey"
          >
            <el-option v-for="item in sensor" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阈值：" :label-width="formLabelWidth">
          <el-input v-model="preValue" placeholder="请输入阈值" class="input-w-480"></el-input>
        </el-form-item>
        <el-form-item label="坐标：" :label-width="formLabelWidth">
          <el-input v-model="x" placeholder="请输入x坐标" class="input-w-480"></el-input>
          <el-input v-model="y" placeholder="请输入y坐标" class="input-w-480"></el-input>
          <el-input v-model="z" placeholder="请输入z坐标" class="input-w-480"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="buttonEdit = false">取消</el-button>
        <el-button type="primary" @click="submitButtonEdit">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="row.name" :visible.sync="buttonAllocaTion" :modal="false">
      <el-form :model="buttonFrom">
        <el-form-item label="初始值：" :label-width="formLabelWidth">
          <el-input v-model="buttonFrom.name" placeholder="请输入名称" class="input-w-480"></el-input>
        </el-form-item>
        <el-form-item label="告警设置：" :label-width="formLabelWidth">
          <el-form-item label="增幅值：">
            <el-input v-model="buttonFrom.zengzhi" placeholder="请输入名称" class="input-w-220"></el-input>
          </el-form-item>
          <el-form-item label="累计值：">
            <el-input v-model="buttonFrom.leizhi" placeholder="请输入名称" class="input-w-220"></el-input>
          </el-form-item>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="buttonAllocaTion = false">取消</el-button>
        <el-button type="primary" @click="submitButtonAllocaTion">确定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
export default {
  props: {
    projectId: Number,
    required: true
  },
  data() {
    return {
      x:'',
      y:'',
      z:'',
      alarmValue:{},
      preValue:'',
      treeid:'',//树id
      id: "",
      index: "-1",
      data5: [],
      token:'',
      name:'',
      sensorName:'',
      activeName: "second",
      formLabelWidth: "120px",
      devicePointsAddmonitorContent: "",
      treeAdd: false,
      treeNodeadd: false,
      treeNodeEdit: false,
      buttonAdd: false,
      buttonEdit: false,
      buttonAllocaTion: false,
      relevance: false,
      elmain: false,
      relevan: {},
      tableData: [],
      devicePointsAddsensor: "",
      devicePointsEditsensor: "",
      monitorContentId: [],
      devicePointsEdit: {},
      totalRecord: 0,
      totalPage: 0,
      currentPage: 1,
      form: {},
      treeType: [],
      projectList: {},
      devicePointsAdd: {},
      sensor: [],
      monitorContent: [],
      buttonFrom: {},
      monitorType: {
        name: ""
      },
      treeNodeEditdata: {
        id: "",
        name: "",
        treeType:'',
      },
      treeNodeAdddata: {
        id: ""
      },
      id: "",
      groupInfosList: {},
      props: {
        label: "name",
        children: "child"
      },
      mainTable: {
        mianBreadcrumb: ""
      },
      row: [],
      noData: [],
      yesData: []
    };
  },
  methods: {
    handleClick(tab, event) {
      
    },
    selectKey(id) {
      this.id = id;
      let obj = {};
      obj = this.treeType.find(item => {
        return item.id === id;
        this.id = obj.id;
      });
    },
    selectKey1(id) {
      this.id = id;
      let obj = {};
      obj = this.treeType.find(item => {
        return item.id === id;
        this.id = obj.id;
      });
    },
    monitorContentSelectKey(id) {
      this.id = id;
      let obj = {};
      obj = this.monitorContent.find(item => {
        return item.id === id;
        this.id = obj.id;
      });
    },
    sensorSelectKey(id) {
      this.id = id;
      let obj = {};
      obj = this.sensor.find(item => {
        return item.id === id;
        this.id = obj.id;
      });
    },
    submitTreeAdd() {
      let data = {
        name: this.form.name,
        projectId: this.projectId,
        "monitorContent.id": this.form.treeType,
        creator: this.name,
        parentId: this.index
      };
     
      this.projectModel
        .insertAdd(data)
        .then(res => {
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            var projectId = this.projectId;
            this.projectModel
              .getByPrjId(projectId)
              .then(res => {
                this.data5 = res;
              })
              .catch(err => {
                console.log(err.message);
              });
            this.treeAdd = false;
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log(err.message);
        });
    },
    submitRelevance() {},
    button(data) {
      this.row = data
      this.elmain = true;
      let mc = "";
      if (data.monitorType.length == 1 && data.monitorType[0]) {
        mc =
          " (分组类型：" +
          data.monitorType[0].name +
          " 分组码：" +
          data.monitorType[0].code +
          ")";
      }
      (this.mainTable.mianBreadcrumb =
        data.name + " [ID:" + data.id + "]" + mc),
        (this.mainTable.groupId = data.id);
      let getData = {
        groupId: this.mainTable.groupId,
        currentPage: this.currentPage,
        pageSize: "10"
      };
      this.projectModel
        .devicePointsList(getData)
        .then(res => {
          this.totalRecord = res.data.data.totalRecord;
          this.totalPage = res.data.data.totalPage;
          this.tableData = res.data.data.list;
        })
        .catch(err => {
          console.log(err.message);
        });

      let PointData = {
        projectId: this.projectId,
        monitorItemId: data.monitorType[0] ? data.monitorType[0].id : undefined,
        resultType: 1
      };
      
      this.projectModel
        .queryPoint(PointData)
        .then(res => {
          this.noData = res.data;
        })
        .catch(err => {
          console.log(err.message);
        });

      let yeData = {
        groupId: this.mainTable.groupId,
        resultType: 1
      };
      this.projectModel
        .queryPoint(yeData)
        .then(res => {
          var yeData1 = [];
          for (var i = 0; i < res.data.length; i++) {
            yeData1.push(res.data[i].id);
          }
          this.yesData = yeData1;
        })
        .catch(err => {
          console.log(err.message);
        });
    },
    // 添加测点
    submitButtonAdd() {
      let data = {
        groupId: this.mainTable.groupId,
        name: this.devicePointsAdd.name,
        projectId: this.projectId,
        "monitorContent.id": this.devicePointsAddmonitorContent,
        deviceCollectId: this.devicePointsAddsensor,
      };
      this.projectModel
        .devicePointsAdd(data)
        .then(res => {
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            this.buttonAdd = false;
            this.handleCurrentChange(event);
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          this.$message({
            type: "info",
            message: res.msg
          });
        });
    },
    // 删除
    deleteRow(index, row) {
      this.$confirm("是否要删除?", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {         
          let data = {
            groupId:this.mainTable.groupId,
            pointId:row.id
          }
          this.projectModel
            .devicePointsRemove(data)
            .then(res => {
              this.tableData.splice(index, 1);
            })
            .catch(err => {
              console.log(err.message);
            });    
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {  
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    
    handleEdit(index, row) {
      (this.buttonEdit = true);
      this.devicePointsEdit.groupId = row.groupId;
      this.devicePointsEdit.id = row.id;
      this.devicePointsEdit.name = row.name;
      this.devicePointsEditsensor = row.deviceCollectId;
      this.sensorName = this.collectName
      this.monitorContentId = row.monitorContent.id;
      this.preValue = row.alarmValue;
    },
    //修改测点
    submitButtonEdit() {
      let data = {
        groupId: this.devicePointsEdit.groupId,
        id: this.devicePointsEdit.id,
        name: this.devicePointsEdit.name,
        deviceCollectId: this.devicePointsEditsensor,
        "monitorContent.id": this.monitorContentId,
        alarmValue:this.preValue,
        x:this.x,
        y:this.y,
        z:this.z
      };
      this.projectModel
        .devicePointsUpData(data)
        .then(res => {
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            this.buttonEdit = false;
            this.handleCurrentChange(event);
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          this.$message({
            type: "info",
            message: res.msg
          });
        });
    },
    allocaTion(index, row) {
      (this.buttonAllocaTion = true);
      this.row = row;
    },
    submitButtonAllocaTion() {},
    append(data) {
      this.treeid = data.id;
      this.treeNodeadd = true;
    },
    submitTreeNodeAdd() {
      let data = {
        name: this.treeNodeAdddata.name,
        projectId: this.projectId,
        "monitorContent.id": this.treeNodeAdddata.treeType,
        parentId: this.treeid,
        brief: ""
      };
      this.projectModel
        .insertAdd(data)
        .then(res => {
          
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            var projectId = this.projectId;
            this.projectModel
              .getByPrjId(projectId)
              .then(res => {
                this.data5 = res;
              })
              .catch(err => {
                console.log(err.message);
              });
            this.treeNodeadd = false;
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log(err.message);
        });
    },
    remove(node, data) {
      this.$confirm("是否要删除?", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var groupId = data.id;
          this.projectModel
            .groupInfosDelete(groupId)
            .then(res => {
              this.tree();
            })
            .catch(err => {
              console.log(err.message);
            });
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    edit(data) {
      this.treeNodeEditdata.id = data.id;
      this.monitorType.name = data.monitorType.name;
      this.treeNodeEditdata.treeType= data.monitorType[0] != null ? data.monitorType[0].id : null;
      this.treeNodeEditdata.name = data.name;
      this.treeNodeEdit = true;
    },
    //树形编辑子节点
    submitTreeNodeEdit() {
      let data = {
        projectId: this.projectId,
        name: this.treeNodeEditdata.name,
        "monitorContent.id": this.treeNodeEditdata.treeType,
        id: this.treeNodeEditdata.id,
      };
      this.projectModel
        .groupInfosUpDate(data)
        .then(res => {
          if (res.status === 200) {
            this.$message({
              type: "success",
              message: res.msg
            });
            var projectId = this.projectId;
            this.tree();
            this.treeNodeEdit = false;
          } else {
            this.$message({
              type: "info",
              message: res.msg
            });
          }
        })
        .catch(err => {
          console.log(err.message);
        });
    },

    handleCurrentChange(event) {
      let getData = {
        groupId: this.mainTable.groupId,
        currentPage: this.currentPage,
        pageSize: "10"
      };
      this.projectModel
        .devicePointsList(getData)
        .then(res => {
          this.totalRecord = res.data.data.totalRecord;
          this.totalPage = res.data.data.totalPage;
          this.tableData = res.data.data.list;
        })
        .catch(err => {
          console.log(err.message);
        });
    },

    handlePreClick(event) {
      if (this.currentPage != 1) {
        this.currentPage--;
      }
    },
    handleNextClick(event) {
      if (this.currentPage != this.totalPage) {
        this.currentPage++;
      }
    },
    //时间格式化
    dateFormat: function(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    tree() {
      var projectId = this.projectId;
      this.projectModel
        .getByPrjId(projectId)
        .then(res => {
          this.data5 = res;
        })
        .catch(err => {
          console.log(err.message);
        });
    },
    //关联测点穿梭框
    handleChange(value, direction, movedKeys) {
      if (direction === "right") {
        this.projectModel
          .PointBatch(this.mainTable.groupId, value)
          .then(res => {
            this.$message({
              type: "succes",
              message: res.msg
            });
            this.handleCurrentChange(event);
          })
          .catch(err => {
            console.log(err.message);
          });
      }
      if (direction === "left") {
        this.projectModel
          .PointBatch(this.mainTable.groupId, value)
          .then(res => {
            this.$message({
              type: "succes",
              message: res.msg
            });
            this.handleCurrentChange(event);
          })
          .catch(err => {
            console.log(err.message);
          });
      }
    }
  },
  mounted() {
    this.token = sessionStorage.getItem("token")
     this.userModel.userToken(this.token).then(res => {
         this.name = res.data.name
      }).catch(err => {
        console.log(err.message)
      })

    var projectId = this.projectId;
    this.tree();
    this.projectModel
      .monitorContent()
      .then(res => {
        this.treeType = res.data;
        this.monitorContent = res.data;
      })
      .catch(err => {
        console.log(err.message);
      });
    this.projectModel
      .getById(projectId)
      .then(res => {
        this.projectList = res.data;
      })
      .catch(err => {
        console.log(err.message);
      });
    this.projectModel
      .groupInfosId(projectId)
      .then(res => {
        this.groupInfosList = res.data;
      })
      .catch(err => {
        console.log(err.message);
      });
    this.sensorModel
      .devicePointsList()
      .then(res => {
        this.sensor = res.data;
      })
      .catch(err => {
        console.log(err.message);
      });
  }
};
</script>
<style>
.input-w-220 {
  width: 220px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 3px;
}
.el-aside {
  border-right: 1px solid #dfdbdb;
  margin-bottom: 60px
}

.el-dialog {
  width: 36%;
}
.el-tabs__nav {
  float: none;
  text-align: center;
}
.el-tabs__active-bar {
  left: 50px;
}
.treeAdd {
  color: #409eff;
}
.breadcrumb {
  height: 27px;
  border-bottom: 1px solid #dfdbdb;
  margin-bottom: 5px;
}
.button-add {
  float: left;
}
</style>